package com.panshi.controller;

import com.panshi.vo.WebAdmin;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@Slf4j
public class LoginContreller {

    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @PostMapping("/admin/login")
    public String adminLogin(String name,String pwd){
        log.info("账号{},密码{}",name,pwd);

        //封装用户登录数据   生成token
        UsernamePasswordToken token = new UsernamePasswordToken(name,pwd);
        //开启记住我功能
        token.setRememberMe(true);
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        try {
            //执行登录方法  无异常登录  异常退出登录
            subject.login(token);
            log.info("登录成功-----------------------");
            WebAdmin admin = (WebAdmin) subject.getPrincipal();

            return "index";
        }catch (UnknownAccountException e){
            log.info("账号输入错误---------------------");
            return "login";
        }catch (IncorrectCredentialsException e){
            log.info("密码输入错误-----------------------");
            return "login";
        }

    }

    //未授权
    @RequestMapping("/unauthorized")
    @ResponseBody
    public String unauthorized(){
        return "无权访问页面";
    }

}
